<?php

namespace app\api\controller\ec;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;

/**
 * 公共接口
 * 第一步:先添加客户 到ec
 * 第二步:根据客户手机号 获取CrmId
 * 第三步：根据CrmId 获取客户信息
 */
class Ecautotuisong extends Ecbase {

    public function _initialize() {
        parent::_initialize();
    }
    
    /**
     * 废弃客户入库  while
     */
    public function tuisongFeiqiKehu(){
        
        while (true){
            $controller = '\app\common\controller\zhongzhuan\Autoassigncd';
            $param = [];
            $data = call_user_func_array(array($controller, 'startAssign'),array($param));
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }



    /**
     * A B类客户入库
     */
    public function assignKehu(){
       
        while (true){
            //$status 0 暂停   1 分配中  2 分配完成
            $list = db('ec_assign_kehu')->order('id desc')->where('status','<>',2)->select();


            foreach ($list as $key=>$value){

                if(empty($value['auto_assign']))                continue;

                $assing_kehu_detail = db('ec_assign_kehu_detail')->field('SUM(people - success_people) daifenpei,yixiang_id')->where('assign_id',$value['id'])->group('yixiang_id')->select();

                $kehu_list = array();
                foreach ($assing_kehu_detail as $k =>$v){
                    if(empty($v['daifenpei']))                    continue;
                    $yixiang_value = db('ec_ai_task_phone_yixiang')->where('id',$v['yixiang_id'])->value('yixiang_value');
                    $temp_list= db('ec_ai_task_phone')->field('id byid,callJobId,customerTelephone,customerName,callInstanceId,yixiang_txt,yixiang_value,startTime')->where([
                        'yixiang_value'=>$yixiang_value,
                        'status'=>0
                    ])->limit($v['daifenpei'])->order('startTime desc')->select();
                    $kehu_list = array_merge($kehu_list,$temp_list);
                }


                foreach ($kehu_list as $kehu_info){
                    $yixiang_id = db('ec_ai_task_phone_yixiang')->where('yixiang_value',$kehu_info['yixiang_value'])->value('id');
                    $kehu_info['yixiang_id'] = $yixiang_id;
                    $controller = '\app\common\controller\zhongzhuan\Autoassign';
                    $param = ['assign_id'=>$value['id'],'kehu_info'=>$kehu_info];
                    $data = call_user_func_array(array($controller, 'startAssign'),array($param));                
                }

            }
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
               
    }

    
    /** 
     * 推送客户 
     */
    public function addCustomer(){
        while (true){
            $list = db('ec_aiuser_to_ecuser')->where(['status'=>0])->select();
        
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            $end_list = [];
            foreach ($list as $value){
                $content = json_decode($value['content'],true);
                $end_list[] = $content;
            }
            $param = [
                'kehu_list' => $end_list,
                'opt_userid'=>$this->optUserId,
            ] ;

            $controller = '\app\common\controller\zhongzhuan\Fenpei';
            $data = call_user_func_array(array($controller, 'addCustomer'), array($param));
            
//            usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
        
        
        
    }
    
    
    /**
     * 更新客户标签  while
     */
    public function ownUpdateKehuLabel(){
        
        while (true){
            
            $yixiang_label_config = [
                'A'=>'84726558','B'=>'84736557','C'=>'84734554','D'=>'84732560','E'=>'84728556','F'=>'84732561'
            ];

            $label_config = [
                '84731318', //客户来源 【新增百应】
            ];

            $list = db('ec_aiuser_to_ecuser')->where(['label_laiyuan_biaoji_status'=>0])->where('crmId','<>','')->select();
            
            if(empty($list)){
                usleep(5000000);
                continue;
            }
            
            
            $end_list = [];
            foreach ($list as $value){
                $end_list[$value['yixiang_value']][] = $value;
            }

            foreach ($end_list as  $key=>$value){
                $item_kehu_ids = $crmIds = [] ;
                foreach ($value as $k=>$v){
                    $crmIds[] = $v['crmId'];
                    $item_kehu_ids[] = $v['id'];
                }

                $tmp_label = $label_config;
                $tmp_label[] = $yixiang_label_config[$key];            
                $param = ['crmIds' => implode(',', $crmIds),'optUserId'=>$this->optUserId,'labels'=>implode(',', $tmp_label)] ;
                $controller = '\app\common\controller\zhongzhuan\Fenpei';
                $item_response = call_user_func_array(array($controller, 'updateKehuLabel'), array($param));

                if($item_response['code'] == 200){
                    db('ec_aiuser_to_ecuser')->where('id','in',$item_kehu_ids)->setField('label_laiyuan_biaoji_status',1);
                }
            }
            
            // usleep() 函数延迟执行当前脚本若干微秒（一微秒等于一百万分之一秒）。 延迟5秒
            usleep(5000000);
        }
        
    }
    
    

    
    
    
    
    
    
    
    public function batchGetKehuList(){
        
        
        $field_id_config = config('zhongzhuan.field');
        $yixiang_field_id = $field_id_config['yixiang']['fieldid'];
        $baiying_luyin_field_id = $field_id_config['baiying_luyin']['fieldid'];
        
        $currentPage = 1;
              
        
        
        while (true){
            $controller = '\app\common\controller\zhongzhuan\Fenpei';            
                        
            $item_param = ['pageNo'=>$currentPage,'pageSize'=>200,'createUserIdList'=>[$this->optUserId]];
            $response = call_user_func_array(array($controller, 'getKehuInfoByOptUserid'), array($item_param));         
            
            if($response['code'] == 200){
                foreach ($response['data']['list'] as $key => $value){
                    
                    $yixiang_txt = $baiying_luyin = '';
                    
                    foreach ($value['fieldInfos'] as $k =>$v){
                        foreach ($v as $item_k =>$item_v){
                            if($item_k == $yixiang_field_id){
                                $yixiang_txt = $item_v;
                            }else if($item_k == $baiying_luyin_field_id){
                                $baiying_luyin = $item_v;
                            }
                        }

                    }
                                     
                    
                    
                    $exist_ = db('ec_kehu')->where('crmId',$value['crmId'])->count();
                    if(!empty($exist_)){
                        db('ec_kehu')->where('crmId',$value['crmId'])->update([       
                            'addtime'=> strtotime($value['createTime']),
                            'name'=> $value['name'],
                            'yixiang_txt'=>$yixiang_txt,
                            'record_file'=>$baiying_luyin,
                            'content'=> json_encode($value,JSON_UNESCAPED_UNICODE),
                        ]);
                    }else{
                        $insert_data[] = [
                            'crmId'=>$value['crmId'],
                            'mobile'=>$value['mobiles'][0],
                            'name'=> $value['name'],
                            'yixiang_txt'=>$yixiang_txt,
                            'record_file'=>$baiying_luyin,
                            'addtime'=>strtotime($value['createTime']),
                            'follow_userid'=>$value['followUserId'],
                            'content'=> json_encode($value,JSON_UNESCAPED_UNICODE),
                            'createtime'=>time(),
                        ];
                    }
                }
                if(!empty($insert_data)){
                    db('ec_kehu')->insertAll($insert_data);
                }
                
                
                $currentPage = $response['data']['page']['pageNo'] + 1;
                if($currentPage > $response['data']['page']['maxPageNo']){
                    $msg = '成功';
                    break;
                }
            }else{
                $msg = '失败';
                break;
            }
        }
        
        
        
        
        $this->success('成功',$response);
    }
    
    
    
    public function ownUpdateKehuInfo(){
        $kehu_list = db('ec_kehu')->where('id',15)->order('id desc')->limit(1)->select();
        
        $luyin_domain_prefix = config('zhongzhuan.luyin_domain_prefix'); 
        
        $field_config = db('ec_map_fields')->column('fieldId');
//        $data  = [["crmId"=>2460694917,"name"=>"小原梨子1111","optUserId"=>7769329]]; 
        $list = [];
        foreach ($kehu_list as $value){
            $org_info = json_decode($value['content'],true);
            
            if(empty($org_info)){
                $this->error('是吧');
            }
            
            $by_kehu_info = db('ec_ai_task_phone')->field('customerTelephone,callInstanceId')->where('customerTelephone',$value['mobile'])->order('id desc')->find();
            
            
            $fields =[];
            
            foreach ($org_info['fieldInfos'] as $k =>$v){
                $field_keys = array_keys($v);
                foreach ($field_keys as $item_k){
                    if(empty($by_kehu_info)){
                        $fields[$item_k] = empty($v[$item_k])?'':$v[$item_k];
                        continue;
                    }
                    
                    
                    if(in_array($item_k, $field_config)){                                                
                        if($item_k == '82720068'){  //百应录音                            
                            $fields[$item_k] = $luyin_domain_prefix .'?callInstanceId=' .$by_kehu_info['callInstanceId'];                            
                        }else{ //意向度
                            $fields[$item_k] = empty($v[$item_k])?'':$v[$item_k];
                        }
                    }
                }
               
            }
                     
           
            $list[] = [
                "crmId"=>$value['crmId'],"optUserId"=>$this->optUserId,"name"=>$org_info['name'],"fields"=>$fields,
                 "mobile"=>$value['mobile']
            ];
          
            
            
        
        }       
        $controller = '\app\common\controller\zhongzhuan\Fenpei';
        $data = call_user_func_array(array($controller, 'updateInfo'), array(['list'=>$list]));
        $this->success('',$data);
    }
    
  
}
